package cn.wzl.getapmac;

import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class GetApMacActivity extends Activity implements
		WifiScanReceiver.WifiScanReceiverSink {
	/** Called when the activity is first created. */
	private WifiManager wifiManager = null;
	List<ScanResult> scanResultList = null;
	WifiScanReceiver wifiScanReceiver = null;
	Handler handler = null;

	private TextView scanResultTV;

	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case StaticMessage.WIFI_SCAN_RESULT:
				StringBuffer sb = new StringBuffer();
				for (ScanResult scanResult : scanResultList) {
					sb.append(scanResult.SSID).append("-------------")
							.append(scanResult.BSSID).append("\n");
				}
				if (scanResultTV != null)
					scanResultTV.setText(sb);
				break;
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		scanResultTV = (TextView) findViewById(R.id.scan_result);
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifiScanReceiver = new WifiScanReceiver(wifiManager, this);
		handler = new MyHandler();
	}

	@Override
	protected void onResume() {
		registerReceiver(wifiScanReceiver, new IntentFilter(
				WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		super.onResume();
	}

	@Override
	protected void onPause() {
		unregisterReceiver(wifiScanReceiver);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (handler != null)
			handler = null;
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public void onClickButton1(View v) {
		if (wifiManager != null) {
			if (!wifiManager.isWifiEnabled()) {
				wifiManager.setWifiEnabled(true);
			}
			wifiManager.startScan();
		}
	}

	@Override
	public void onScanFinish(List<ScanResult> scanResult) {
		if (handler != null) {
			scanResultList = scanResult;
			handler.sendEmptyMessage(StaticMessage.WIFI_SCAN_RESULT);
		}
	}
}
